<!-- 文件引用 -->
<link rel="stylesheet" href="/static/layui_extends/mouseRightMenu/mouseRightMenu.css" />
<link rel="stylesheet" href="/static/cloud/css/cloud.css" />

<!-- 样式代码 -->
<style type="text/css">
	.content {
		margin: 20px;
	}

	.content ul {
		padding-top: 10px;
		padding-bottom: 10px
	}

	.content .layui-nav .url {
		padding-right: 0.5rem;
		padding-left: 0.5rem;
		cursor: pointer;
		text-align: center;
		line-height: 40px
	}

	.content .bar {
		margin-bottom: 0.5rem
	}

	.content .layui-nav {
		background: white;
		color: #6d6d6d;
		padding: 0
	}

	.content .table_file_name {
		color: #00986f;
	}

	.content .table_file_name:hover {
		cursor: pointer;
		color: #5fb878;
	}

	.content .forbid {
		color: #cacaca
	}

	/* 目录格式标签 */
	.path-bar a,.file-list-content tr td{
		cursor: pointer;
	}
	.path-bar .path-conment .layui-icon{
		color: #b1b1b1;
	}

	/* .table-bar-operation-item:hover{
		visibility: visible;
	}

	.table-bar-operation-item{
		visibility:hidden;
	} */

	.fast-menu{
		float: right;
	}

	/* 修复表格勾选错位 */
	.layui-table-cell .layui-form-checkbox[lay-skin=primary]{
		top: 5px;
    	padding: 0;
	}
</style>

<!-- 页面代码 -->

<div class="content">
	<!-- 隐藏上传标签 -->
	<input type="file" name="mof" multiple="multiple" data-upload_path='/' class="layui-hide" id="upload_file" />
	<input  class="layui-hide" id="FILE_LIST_TAG" value="" />
	
	<div class="cloud-card bar">
		<!-- <div class="layui-inline">
			<div class="layui-btn-group">
				<button class="layui-btn layui-btn-primary layui-btn-xs" id="menu_more">
					<i class="layui-icon layui-icon-more"></i>
				</button>
				<button class="layui-btn layui-btn-primary layui-btn-xs" id="back">
					<i class="layui-icon layui-icon-left"></i>
				</button>
			</div>
		</div> -->
		<div class="layui-inline path-bar" id="path">
			<div class="layui-inline">
				<i class="layui-icon layui-icon-more-vertical line" style="color: black;"></i>
				<!-- <a data-filename="/" data-path="" data-fileid="0" id="path-conment-item-root">根目录</a> -->
			</div>
			
			<div class="layui-inline path-conment">
				<!-- <div class="layui-inline path-conment-item">
					<i class="layui-icon layui-icon-right line"></i>
					<a data-filename="9633" data-path="/" data-id="123" id="path-conment-item-1612620983364">9633</a>
				</div> -->
			</div>
			
			
		</div>
		<div class="layui-inline fast-menu">
			<button class="layui-btn layui-btn-xs layui-btn-primary fast-menu-btn-paste layui-hide" id="paste_btn">粘贴</button>

			<div class="layui-btn-group">
				<button class="layui-btn layui-btn-xs layui-btn-primary fast-menu-btn-move layui-hide" id="move_btn">剪切</button>
				<button class="layui-btn layui-btn-xs layui-btn-primary fast-menu-btn-copy layui-hide" id="copy_btn">复制</button>
			</div>
			
			
			<div class="layui-btn-group">
				
				<button class="layui-btn layui-btn-xs layui-btn-primary fast-menu-btn-upload" id="upload_btn">上传文件</button>
				<button class="layui-btn layui-btn-xs layui-btn-primary fast-menu-btn-0" id="add_new_dir">新建文件夹</button>
				<button class="layui-btn layui-btn-xs layui-btn-primary fast-menu-btn-0" id="upload_list_open">上传列表</button>
				<!-- <button class="layui-btn layui-btn-xs layui-btn-primary" id="upload_list_open">多选</button>
				<button class="layui-btn layui-btn-xs layui-btn-primary" id="upload_list_open">删除</button>
				<button class="layui-btn layui-btn-xs layui-btn-primary" id="upload_list_open">复制</button> -->
				<!-- <button class="layui-btn layui-btn-xs layui-btn-primary" id="upload_list_open">粘贴</button> -->
			</div>
		
		</div>
	</div>
	<div class="cloud-card table layui-unselect file-body" id="checkImgWindow">
		<table class="layui-hide" id="data-table" lay-filter="data-table"></table>
	</div>
		<!-- </div> -->
	</div>
</div>

<!-- 模板代码 -->

<!-- 文件图标模板 -->
<script type="text/html" id="table-bar-image">
	{{# if(d.type==2){  }}
		<img style="width: 1.5rem" src="/static/layui_extends/fileManager/img/dir.png">
	{{# }else{ }}
		<img style="width: 1.5rem" src="/static/layui_extends/fileManager/img/{{app.getExtendName(d.file_name,true)}}.png" onerror="this.src='/static/layui_extends/fileManager/img/none.png'">
	{{# } }}
</script>

<!-- 文件尺寸模板 -->
<script type="text/html" id="table-bar-size">
	{{# if(d.size==0){ }}
		0 B
	{{# }else if(d.size){ }}
		{{app.bytesToSize(d.size)}}
	{{# }else{ }}
		-
	{{# } }}
</script>

<!-- 文件名模板 -->
<script type="text/html" id="table-file-name-tpl">
	{{# if(d.type==2){ }}
	<div title="{{d.file_name}}">{{d.file_name}}</div>
	{{# }else{ }}
	<div class="table_file_name" lay-event="detail" title="{{d.file_name}}">{{d.file_name}}</div>
	{{# } }}
</script>

<script type="text/html" id="table-bar-operation">
	<!-- <a class="layui-btn layui-btn-xs" lay-event="open">打开所在目录</a> -->
	<div class="table-bar-operation-item">
		<a class="layui-btn layui-btn-primary layui-border-blue layui-btn-xs" lay-event="rename" data-id={{d.id}}>重命名</a>
		<a class="layui-btn layui-btn-primary layui-border-red layui-btn-xs" lay-event="del" data-id={{d.id}}>删除</a>
	</div>
	
</script>

<script type="text/javascript">
	layui.use(['table','mouseRightMenu', 'upload', 'my_upload'], function () {
		var table = layui.table, $ = layui.$;
		var mouseRightMenu = layui.mouseRightMenu;
		var my_upload = layui.my_upload;

		var CurrentPath = {path:'/',pathId:0};//当前路径
		var CheckFileList = [];// 选中文件
		var CheckFileStatus=0;//0.无操作 1.移动 2.复制
		var CheckFilePath='';
		var getFileListUrl= "/api/file/getPathList";
		
		// var FileObj = { path: '/', pathId: 1 };//文件对象
		
		$("title").text('我的文件 - 私有云盘');
		var type = app.parseUrl().params.type || 1;
		var url = ['getCollectList', 'getUploadList', ''];
		// console.log(type);
		app.setTopMenu('/index/file_list');
		$('.content .layui-nav .url').click(function () {
			app.go($(this).attr('data-href'))
		})

		$('.content .layui-nav-item[data-id=' + type + '] div').addClass('layui-this')
		var cols = [
			{ type: 'checkbox', fixed: 'left' }
			// {field:'id', title: 'ID', sort: true}
			, { field: '', title: '', toolbar: '#table-bar-image', width: 60, align: 'center' }
			, { field: 'file_name', title: '文件名',sort:true,toolbar:"#table-file-name-tpl"}
		];

		if (!app.isMobile()) {
			cols.push({ field: 'size', title: '大小',toolbar:'#table-bar-size' , sort: true});
			cols.push({ field: 'update_time', title: '日期' , sort: true});
			
			if (type == 1) {
				cols.push({ title: '操作', toolbar: '#table-bar-operation', align: 'center' });
			}
		}

		table.render({
			elem: '#data-table'
			,id:'data-table'
			, url: ''//刚进页面不加载列表
			, headers: {'Token':app.getToken()}//刚进页面不加载列表
			, where:{'path': CurrentPath['path'],'returnType':'layui'}
			, method: 'post' //如果无需自定义HTTP类型，可不加该参数
			, cellMinWidth: 80 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
			, skin: 'line'
			, cols: [cols]
			, height:'full-190'
		});

		// 添加路径项目
		function addPathContentItem(path,fileid,filename,filename_text, hide_arrow_icon){
			var filename_text = filename_text|| filename;

			var num_id = "path-conment-item-"+(Date.parse(new Date())+ Math.round(Math.random() * 1000));
			var html='';
			html += '<div class="layui-inline path-conment-item">';
			if(hide_arrow_icon!==true && filename!=''){
				html += '<i class="layui-icon layui-icon-right line"></i>';
			}
			html += '<a data-filename="'+ filename+'" data-path="'+ path+'" data-fileid="'+ fileid+'" id="'+ num_id+'">'+ filename_text+'</a></div>';
			$('.path-conment').append(html);

			// 监听目录模板被点击，加入判断是不是和上次重复 重复采用刷新
			$('#'+ num_id).click(function(){
				// console.log($(this).data('filename'), $(this).data('path'), $(this).data('fileid'));
				if(onPathContentItem($(this).data('fileid'), $(this).data('filename'), $(this).data('path'))!==false){
					console.log($(this));
					// 删除后面所有元素
					$(this).parent().nextAll().remove()
				}
			})
		}

		// 清理路径项目
		function cleanPathContentItem() {
			$('.path-conment').html('');
		}
		

		// 监听
		function onPathContentItem(fileid, filename, path){
			openPath(path, filename,0,2)
		}

		// 读取文件列表加载
		function loadFileList(path){
			console.log('加载文件夹列表',path);
			var data = {};
			data['path'] = path;
			data['returnType'] = 'layui';
			table.reload('data-table', {
				url: getFileListUrl
				, where: data //设定异步数据接口的额外参数
			})
		}

		// 根据路径打开路径【可能临时，无id】
		// mode 模式 1.初始化（） 2.只设置地址，不执行列表刷新
		function openPathByPath(url_path, mode){
			var pathArr = url_path.split('/');
			var pathStr = '';
			for (let i = 0; i < pathArr.length; i++) {
				if (i == pathArr.length - 1) {
					break;
				}
				if (pathArr[i] == '') {
					pathStr += pathArr[i];
				} else {
					pathStr += '/' + pathArr[i];
				}
			}
			openPath(pathStr, pathArr[pathArr.length - 1], 0, mode);
		}

		// 打开指定路径
		// mode 模式 1.初始化（） 2.只设置地址，不执行列表刷新
		function openPath(path, filename,fileid,mode) {
			var new_path = (path == '/' ? path : (path + '/')) + filename;
			// 清空列表内容
			$('.file-list-content').html('');
			// 添加路径
			var paths = new_path.split('/');
			// console.log(paths);
			
			// 判断是否为初始化，非初始化采用追加
			if(mode==true || mode==1){
				cleanPathContentItem();
				for (let i = 0; i < paths.length; i++) {
					const element = paths[i];
					// 第一个是根目录
					if (i == 0) {
						addPathContentItem('/', '0', '', '根目录', true);//根目录
					} else {
						// 拼接目录
						var tmp_path = '';
						for (let i2 = 0; i2 < paths.length; i2++) {
							// const element = paths[i2];
							if (i == i2) {
								break
							} else {
								// console.log('循环', paths[i2]);
								if (paths[i2] != '') {
									tmp_path += '/' + paths[i2];
								}
							}
						}
						// console.log('目录',tmp_path);
						addPathContentItem(tmp_path, '', element);
					}
				}
			}else if (mode == 2) {
				// 不执行直接设置网址
				app.setUrl(app.parseUrl().path + '?path=' + new_path);
				return;
			}else{
				if (path == '/' && filename == '') {
					addPathContentItem('/', '0', '', '根目录', true);//根目录
				} else {
					addPathContentItem(path, fileid, filename);
				}
				app.setUrl(app.parseUrl().path + '?path=' + new_path);
			}
			
			
			CurrentPath['path'] = new_path;
			
			loadFileList(new_path);
		}


		function getExtendName(_name) {
			if (_name.indexOf('.') == -1) {
				return '';
			}
			var spl = _name.split(".");
			return spl[spl.length - 1];
		}

		function listenBox(){
			$('#'+ 'menu_more').click(function(){
				var buttons = [
					{ id: 'upload', name: '上传文件' },
					{ id: 'show_upload_list', name: '查看上传列表' },
					{ id: 'new_dir', name: '新建文件夹' },
					// { id: 'more_check', name: moreCheckText }
				]

				// if (moreCheckStatus) {
				// 	// buttons.push({id:'copy',name:'复制'})
				// 	buttons.push({ id: 'copy', name: '剪切' })
				// }

				// if (clipboard.ids) {
				// 	buttons.push({ id: 'pates', name: '粘贴' });
				// }


				var html = ''
				for (var i = 0; i < buttons.length; i++) {
					html += '<button class="layui-btn layui-btn-primary" id="' + buttons[i].id + '">' + buttons[i].name + '</button>'
				}
				html = '<div class="fileManager-menu-list">' + html + '</div>';
				layer.open({
					type: 1,
					title: false, //不显示标题栏
					closeBtn: false,
					// area: '101px;',
					shade: 0.5,
					content: html,
					shadeClose: true, //开启遮罩关闭
					success: function (e, i) {

					}
				})
			})

			// 注册监听
			app.hashChangeListen(app.parseUrl().path,function(url){
				// return true;
				console.log('注册监听 回调');
				if(app.getCloudContentPath()== app.parseUrl(url).path){
					console.log('页面相同，不跳转检查参数');
					var path= app.parseUrl(url).params.path;
					openPathByPath(path, true)
					return false;// 阻止跳转
				}

				console.log('页面不同跳转新页面');
				return true;
			})

			// 表格行按钮事件
			table.on('tool(data-table)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
				var data = obj.data; //获得当前行数据
				var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
				var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）
				if (layEvent === 'detail') { //查看
					app.runTpl('file_info', { file_id: data.id })
				} else if (layEvent === 'del') { //删除
					layer.confirm('真的删除行么', function (index) {
						//向服务端发送删除指令
						var postData={};
						// postData['ids']=[data.id];
						postData['fileName']=[]
						postData['fileName'].push((data.path=="/"?("/"+ data.file_name): data.path + "/" + data.file_name));
						app.ajaxPost('/api/file/delete', postData, function () {
							layer.close(index);
							obj.del();//删除对应行（tr）的DOM结构，并更新缓存
							loadFileList(CurrentPath['path']);
						});
					});
				}else if (layEvent === 'rename') { //重命名
					var postData = {};
					layer.prompt({ title: '新名字', formType: 0, value: data.file_name }, function (text, index) {
						var old_ext_name = getExtendName(data.file_name), new_ext_name = getExtendName(text)
						// console.log(old_ext_name, new_ext_name)
						if (old_ext_name != new_ext_name) {
							layer.confirm('新扩展名（' + data.file_name + '）与旧扩展名（' + text + '）不同，确定继续修改吗', {
								btn: ['确定', '取消'] //按钮
							}, function () {
								postData['oldFileName'] = marryPathFileName(data.path, data.file_name) ;
								postData['newFileName'] = marryPathFileName(data.path, text) ;
								app.ajaxPost('/api/file/rename', postData, function (res) {
									// console.log(res);
									if(res['err_code']!=0){
										layer.msg(res['err_msg'])
										return;
									}
									layer.close(index);
									loadFileList(CurrentPath['path']);
								});
							});
						} else {
							
							postData['oldFileName'] = marryPathFileName(data.path, data.file_name);
							postData['newFileName'] = marryPathFileName(data.path, text);
							app.ajaxPost('/api/file/rename', postData, function (res) {
								// console.log(res);
								if (res['err_code'] != 0) {
									layer.msg(res['err_msg'])
									return;
								}
								layer.close(index);
								loadFileList(CurrentPath['path']);
							});
						}

					});
				}
			});

			// 表格行双击事件
			table.on('rowDouble(data-table)', function (obj) {
				// console.log(obj.tr) //得到当前行元素对象
				// console.log(obj.data) //得到当前行数据
				if(obj.data.type!=1){
					// 打开目录
					openPath(obj.data.path, obj.data.file_name, 0,2);
				}else{
					// 打开文件
					app.runTpl('file_info', { file_id: obj.data.id})
				}
			});

			// 上传文件初始化
			my_upload.init({
				uploadUrl: "{:url('api/file/upload')}",
				fileBoxElemId: 'checkImgWindow',
				fileAddElemId: 'upload_file',
				// currentPath:CurrentPath['path'],
				getPostData: function () {
					// return false;
					// var path = fileManager.getNowPath()
					// return {
					// 	path: path.path,
					// 	p_id: path.id
					// }
				},
				uploadSuccess: function (file) {
					// console.log('上传完成 ', file);
					layer.msg('上传完成 ' + (file.cloudpath=='/'?'/': file.cloudpath+'/') + file.name);
					loadFileList(CurrentPath['path']);
				},
				getFile:function(dileList){
					// console.log('得到文件');
					// console.log(dileList);
					// $('#upload_file').data('upload_path', CurrentPath['path']);
					// $('#upload_file').click();
				},
				getUploadPath:function() {
					return CurrentPath['path'];
				}
			})


			// my_upload.getUploadPath(){
			// 	return CurrentPath['path'];
			// }

			table.on('checkbox(data-table)', function (obj) {
				var checkStatus = table.checkStatus('data-table'); //idTest 即为基础参数 id 对应的值
				if (checkStatus.data.length == 0) {
					$('.fast-menu-btn-move').addClass('layui-hide');
					$('.fast-menu-btn-copy').addClass('layui-hide');
				}else{
					$('.fast-menu-btn-move').removeClass('layui-hide');
					$('.fast-menu-btn-copy').removeClass('layui-hide');
				}
				console.log(obj); //当前是否选中状态
				console.log(obj.data); //选中行的相关数据
				console.log(obj.type); //如果触发的是全选，则为：all，如果触发的是单选，则为：one
			});

			// 新建文件夹
			$('#add_new_dir').click(function(){
				layer.prompt({ title: '新文件夹名称', formType: 0 }, function (text, index) {
					var postData={};
					postData['fileName'] = marryPathFileName(CurrentPath['path'], text);
					if(text=='' || text == ' '){
						layer.msg('非法文件名')
						return;
					}
					app.ajaxPost('/api/file/newDir', postData, function (res) {
						if(res.err_code==0){
							layer.close(index);
							layer.msg('新建成功');
							loadFileList(CurrentPath['path']);
						}else{
							layer.alert(res.err_msg);
						}
						// location.reload()
					});
				});
			})

			// 上传按钮
			$('#upload_btn').click(function () {
				// 修改上传路径
				$('#upload_file').data('upload_path', CurrentPath['path']);
				$('#upload_file').click();
			})

			// 打开上传列表
			$('#upload_list_open').click(function () {
				// console.log('888888')
				my_upload.showUploadList();
			})

			// 移动按钮（剪切）
			$('#move_btn').click(function () {
				var checkStatus = table.checkStatus('data-table'); //idTest 即为基础参数 id 对应的值
				if(checkStatus.data.length==0){
					layer.msg('请先勾选要操作的项');
					return;
				}
				var paths=[];
				for (let index = 0; index < checkStatus.data.length; index++) {
					const element = checkStatus.data[index];
					paths.push(element.file_name)
					
				}
				// 显示粘贴按钮
				$('.fast-menu-btn-paste').removeClass('layui-hide');
				
				CheckFilePath = CurrentPath['path'];
				CheckFileList= paths;
				CheckFileStatus=1;
				layer.msg('已经保存的剪切板');
				console.log(paths);
			})

			// 复制（拷贝）按钮
			$('#copy_btn').click(function () {
				var checkStatus = table.checkStatus('data-table'); //idTest 即为基础参数 id 对应的值
				if (checkStatus.data.length == 0) {
					layer.msg('请先勾选要操作的项');
					return;
				}
				var paths = [];
				for (let index = 0; index < checkStatus.data.length; index++) {
					const element = checkStatus.data[index];
					paths.push(element.file_name)

				}
				// 显示粘贴按钮
				$('.fast-menu-btn-paste').removeClass('layui-hide');

				CheckFilePath = CurrentPath['path'];
				CheckFileList = paths;
				CheckFileStatus = 2;
				layer.msg('已经保存的剪切板');
				console.log(paths);
			})

			// 粘贴按钮/粘贴
			$('#paste_btn').click(function () {
				console.log(CheckFileList, CheckFilePath);
				if(CheckFilePath== CurrentPath['path']){
					layer.msg('非法粘贴目录');
					return;
				}
				var postData = {};
				postData['targetPath'] = CurrentPath['path'];// 目标目录
				postData['fileNameList'] = CheckFileList; // 文件名列表
				postData['srcPath'] = CheckFilePath;// 源路径
				console.log(postData)
				// return 
				if(CheckFileStatus==1){
					var layerIndex=loading()
					app.ajaxPost('/api/file/move', postData, function (res) {
						layer.close(layerIndex)
						if(res.data.failResult.length > 0){
							var failStr = "";
							for (let i = 0; i < res.data.failResult.length; i++) {
								const element = res.data.failResult[i];
								failStr+= "<p>"+element+ "</p>"
							}
							layer.alert('部分文件（夹）已存在:' + failStr);
							loadFileList(CurrentPath['path']);
						} else {
							layer.msg('移动完成');
							loadFileList(CurrentPath['path']);
						}

						// 隐藏粘贴按钮
						$('.fast-menu-btn-paste').addClass('layui-hide');
						
						// location.reload()
					});
				}else{
					// console.log('拷贝文件')
					var layerIndex = loading()
					app.ajaxPost('/api/file/copy', postData, function (res) {
						layer.close(layerIndex)
						if (res.err_code !=0) {
							layer.alert(res.err_msg);
						}else if(res.data.failResult.length>0){
							var failStr="";
							for (let i = 0; i < res.data.failResult.length; i++) {
								const element = res.data.failResult[i];
								failStr += "<p>" + element + "</p>"
							}
							layer.alert('部分文件（夹）已存在:'+ failStr);
							loadFileList(CurrentPath['path']);
						}else{
							layer.msg('复制成功');
							loadFileList(CurrentPath['path']);
						}
						// 隐藏粘贴按钮 复制功能 不需要隐藏
						// $('.fast-menu-btn-paste').addClass('layui-hide');

						// location.reload()
					});
				}
				
			})
			
		}
		// 监听集
		listenBox();

		// 获取文件名
		function getFileName(o) {
			var pos = o.lastIndexOf('/');
			return o.substring(pos + 1);
		}

		function loading(msg){
			var msg = msg || "请稍后"
			var index=layer.msg(msg, {
				icon: 16
				, shade: 0.01
				, time: 0
			});
			return index;
		}

		// 组合路径
		function marryPathFileName(path,file_name){
			return path == "/"?("/"+ file_name):( path+ "/" + file_name)
		}

		function start(){
			console.log('当前页面初始化');
			// $('.table').height($(window).height()-150);

			// 初始化打开路径
			var url_path = app.parseUrl().params.path;
			if (url_path) {
				// CurrentPath['path']= url_path;
				console.log('初始化目录', url_path);
				if (url_path == '/') {
					openPath('/', '', 0);
				} else {
					openPathByPath(url_path, true);
				}
			} else {
				openPath(CurrentPath['path'], '', 0);
			}
			
		}

		start();
	})
</script>